package org.bbelovic.devel.exercises.number.primes;

import static java.util.Arrays.asList;
import java.util.Iterator;
import java.util.List;

public class PrimesUtilities {

    private PrimesUtilities() {

    }

    public static boolean isPrime(final long number) {
        if ((number == 1L) || number != 2L && number % 2 == 0) return false;
        final long sqrt = (long)Math.sqrt(number);
        for (int i = 3; i <= sqrt; i +=2) {
            if (number % i == 0) {
                return false;
            }
        }
        return true;
    }

    public static List<Integer> erathostheneSieve(final List<Integer> input) {
        final int size = input.size();
        final int sqrt = (int) Math.sqrt(input.get(size-1));
        for (int i = 0; i < sqrt; i++) {
            if (input.get(i) == -1) continue;
            int act = input.get(i);
            for (int j = i + act; j < size; j+= act) {
                if (input.get(j) == -1)
                    continue;
                if (input.get(j) % act == 0) {
                    input.set(j, -1);
                }
            }
        }
        return filter(input, Integer.valueOf(-1));
    }

    public static List<Long> getPrimePairForNumber(final Long input) {
        long longValue = input.longValue();
        while (true) {
            if (isPrime(longValue) && isPrime(longValue + 2)) {
                return asList(longValue, longValue + 2);
            }
            longValue++;
        }
    }

    private static List<Integer> filter(final List<Integer> input, final Integer toBeRemoved) {
        if (toBeRemoved == null) {
            throw new IllegalArgumentException("Number to be removed can not be null");
        }
        final Iterator<Integer> it = input.iterator();
        while (it.hasNext()) {
            if (toBeRemoved.equals(it.next())) {
                it.remove();
            }
        }
        return input;
    }
}
